# coding:utf-8
from typing import Union

from PySide6.QtCore import Property, QRectF, Qt, Signal
from PySide6.QtGui import QIcon, QPainter
from PySide6.QtWidgets import QWidget

from ..common import singledispatchmethod, IconBaseEnum


class IconWidget(QWidget):
    """ Icon widget

    Constructors
    ------------
    * IconWidget(`parent`: QWidget = None)
    * IconWidget(`icon`: QIcon | str | IconBaseEnum, `parent`: QWidget = None)
    """
    clicked = Signal()

    @singledispatchmethod
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setIcon(QIcon())

    @__init__.register
    def _(self, icon: IconBaseEnum, parent: QWidget = None):
        self.__init__(parent)
        self.setIcon(icon)

    @__init__.register
    def _(self, icon: QIcon, parent: QWidget = None):
        self.__init__(parent)
        self.setIcon(icon)

    @__init__.register
    def _(self, icon: str, parent: QWidget = None):
        self.__init__(parent)
        self.setIcon(icon)

    def getIcon(self):
        return self._icon

    def setIcon(self, icon: Union[str, QIcon, IconBaseEnum]):
        if isinstance(icon, IconBaseEnum):
            icon = icon.icon()
        elif isinstance(icon, str):
            icon = QIcon(icon)
        self._icon = icon
        self.update()

    def mousePressEvent(self, e):
        if e.button() == Qt.MouseButton.LeftButton:
            self.clicked.emit()

    def paintEvent(self, e):
        painter = QPainter(self)
        painter.setRenderHints(QPainter.RenderHint.Antialiasing |
                               QPainter.RenderHint.SmoothPixmapTransform)
        self._icon.paint(painter, QRectF(self.rect()).toRect(), Qt.AlignmentFlag.AlignCenter)

    icon = Property(QIcon, getIcon, setIcon)
